package com.xunk.common.core.validator;

import com.xunk.common.core.annotation.EnumCheck;
import com.xunk.common.core.interfaces.EnumValidateInterface;
import com.xunk.common.core.utils.StringUtils;
import lombok.SneakyThrows;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @ProjectName: HIM
 * @Package: com.xunk.equipment.validator
 * @ClassName: EnumValidator
 * @Author: luanzhiwei
 * @Description: 枚举校验类
 * @Date: 2021/4/13 9:30
 * @Version: 1.0
 */
public class EnumValidator implements ConstraintValidator<EnumCheck, String> {

    private EnumCheck annotation;


    @SneakyThrows
    @Override
    public void initialize(EnumCheck constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        //是否允许为空
        boolean ignoreEmpty = annotation.ignoreEmpty();
        //不允许为空但实际为空，返回false
        if (!ignoreEmpty && StringUtils.isEmpty(value)) {
            return false;
        }
        //允许为空且实际为空，返回true
        if (ignoreEmpty && StringUtils.isEmpty(value)) {
            return true;
        }
        //不允许为空，且实际不为空，继续校验

        Class<?> clazz = annotation.enableClass();

        // clazz为枚举
        if (clazz.isEnum()) {

            Object[] clazzEnumConstants = clazz.getEnumConstants();
            EnumValidateInterface clazzEnumConstant = (EnumValidateInterface) clazzEnumConstants[0];
            return clazzEnumConstant.isValidEnum(value);
        } else {
            return false;
        }
    }
}
